﻿using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using ZilLion.Core.ConfigManager.Manager;
using ZilLion.TaskManager.Entity.Config;
using ZilLion.TaskManager.Entity.Entity;
using ZilLion.TaskManager.Repository;

namespace ZilLion.TaskManager.Core.Infrastructure
{
    public class TaskRunStateContainer
    {
        private static volatile TaskRunStateContainer _instance;
        private static readonly object Lock = new object();

        private TaskRunStateContainer()
        {
        }
        private static  ITaskStateRespository _taskStateRespository;
        public static TaskRunStateContainer GetInstance()
        {
            if (_instance == null)
                lock (Lock)
                {
                    if (_instance == null)
                    {
                        _instance = new TaskRunStateContainer();
                        _taskStateRespository=new TaskStateRespository();
                        var allTasksockes = _taskStateRespository
                            .GetAllTaskState(ZilLionConfigurationManager.GetConfigInstance<TaskManagerCommonConfig>().ClientNo)
                            ?.TaskStates.ToList();


                        foreach (var state in allTasksockes?.ToList()??new List<TaskStateEntity>())
                        {
                            _instance.TaskStates.AddOrUpdate(state.Taskid, state);
                        }

                    }
                }
            return _instance;
        }
        
        public ConcurrentDictionary<string, TaskStateEntity> TaskStates { get; } =
            new ConcurrentDictionary<string, TaskStateEntity>();
    }
}